<?php
/**
 * 菜单管理
 */
namespace App\Services;

use App\Menu;
use Validator;

class MenusService {

    /**
     * 创建｜更新菜单信息
     * @param \Illuminate\Http\Request $request
     * @return array
     * @author: lxy
     * @time: 2020/6/5 9:32 上午
     * @流程:
     */
    public function createOrUpdateMenu(\Illuminate\Http\Request $request) {
        $data = $request->all();
        $Rules = [
            'title' => 'required|max:255'
        ];
        //非初级菜单需要携带路由信息
        if ( $data['pid'] > 0 ) {
            $Rules['router'] = 'required|max:255';
        }
        try {
            $validator = Validator::make($data, $Rules);
            if ($validator->fails()) {
                //获取第一条错误信息
                $err = $validator->errors()->all()[0];
                throw new \Exception($err);
            }

            if ($data['id'] > 0) {
                $Menu = Menu::find($data['id']);
            } else {
                $Menu = new Menu();
                if ($data['pid'] > 0 ) {
                    $Menu->level = Menu::find($data['pid'])->level + 1;
                } else {
                    $Menu->level = 0;
                }
            }

            $Menu = $this->MenuBindData($Menu,$data);
            $res = $Menu->save();
            if (!$res) {
                throw new \Exception('数据库录入失败');
            }
            $result = [
                'ok'    => true,
                'msg'   => '操作完成'
            ];

            Menu::CacheUpdate();

        } catch (\Exception $e) {
            $result = [
                'ok'    => false,
                'msg'   => $e->getMessage()
            ];
        }
        return $result;
    }

    /**
     * 将请求参数绑定到 Menu 对象（用于添加修改）
     * @param Menu $menu
     * @param array $data
     * @return Menu
     * @author: lxy
     * @time: 2020/6/4 4:15 下午
     * @流程:
     */
    private function MenuBindData(Menu $menu,array $data) {
        $data = array_filter($data);
        foreach ($data as $key => $val) {
            $menu->$key = $val;
        }
        return $menu;
    }

}